/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28 
 */
package com.tzinfo.tzb;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.ClassList.ClassData.ClassSubMenu;
import com.tzinfo.tzb.domain.ForumthreadList;
import com.tzinfo.tzb.domain.ForumthreadList.ForumthreadData;
import com.tzinfo.tzb.domain.ForumthreadList.ForumthreadData.Attachment;
import com.tzinfo.tzb.domain.Hot;
import com.tzinfo.tzb.domain.HotList;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.util.ResFinder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TzbBangForumthreadListActivity2 extends TzbBaseActivity implements
        IXListViewListener {
    // 标志
    private boolean isCreate = true;
    // 参数
    private ClassSubMenu classSubMenu = null;

    // 适配器
    private ImageAdapter imageAdapter;

    // 数据
    private List<Map<String, Object>> data;

    // UI组件
    private YXWXListView listView;
    private ImageView image_theme_title;
    private TextView text_theme_title;
    private RelativeLayout layout_under_top;
    private Animation topInAnimation;
    private Animation topOutAnimation;

    // 其他
    private Handler mHandler;
    private int page = 1; // 页码
    private int pagesize = 10; // 每页条数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tzb_ac_main_bang_forumthreadlist2);
        initParameter();
        initAnimation();
        initUI();
        initData();
        listView.setSelection(TzbCommonData.POSITION);
    }

    private void initParameter() {
        // Intent thisIntent = this.getIntent();
        // classSubMenu = (ClassSubMenu) thisIntent
        // .getSerializableExtra("classSubMenu");
        classSubMenu = TzbCommonData.classSubMenu;
        mHandler = new Handler();
    }

    private void initAnimation() {
        topOutAnimation = AnimationUtils.loadAnimation(
                TzbBangForumthreadListActivity2.this, R.anim.top_out);
        topOutAnimation.setFillBefore(true);
        topOutAnimation.setFillAfter(true);
        topInAnimation = AnimationUtils.loadAnimation(
                TzbBangForumthreadListActivity2.this, R.anim.top_in);
        topInAnimation.setFillBefore(true);
        topInAnimation.setFillAfter(true);
        topInAnimation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                layout_under_top.setVisibility(View.VISIBLE);
                listView.setPadding(0, layout_under_top.getHeight(), 0, 0);
            }
        });
    }

    public void goMore(View view) {
        Intent i = new Intent(this, TzbBangForumthreadListActivity.class);

        startActivity(i);
    }

    private void initUI() {
        // 加载滚动进入条
        mProgressBar = (ProgressBar) this.findViewById(R.id.progressbar_loding);
        image_theme_title = (ImageView) findViewById(R.id.image_theme_title);
        text_theme_title = (TextView) findViewById(R.id.text_theme_title);
        imageLoader.displayImage(classSubMenu.getPicFile() + "",
                image_theme_title, options);
        text_theme_title.setText(classSubMenu.getName());
        listView = (YXWXListView) findViewById(R.id.xListView);
        layout_under_top = (RelativeLayout) findViewById(R.id.layout_under_top);

        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        layout_under_top.measure(w, h);
        int width = layout_under_top.getMeasuredWidth();
        int height = layout_under_top.getMeasuredHeight();

        listView.setPadding(0, height, 0, 0);
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);

        // 设置分类栏的消失动画
        listView.setOnTouchListener(new OnTouchListener() {
            double statrY = 0;
            double endY = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionevent) {
                if (motionevent.getAction() == MotionEvent.ACTION_DOWN) {
                    statrY = motionevent.getY();
                } else if (motionevent.getAction() == MotionEvent.ACTION_MOVE) {
                    endY = motionevent.getY();
                    if ((statrY - endY >= layout_under_top.getHeight() + 30 || (listView
                            .getFirstVisiblePosition() > 1 && statrY - endY >= 30))
                            && listView.getPaddingTop() != 0) {
                        layout_under_top.startAnimation(topOutAnimation);
                        layout_under_top.setVisibility(View.GONE);
                        listView.setPadding(0, 0, 0, 0);
                    } else if (endY - statrY >= 30
                            && listView.getPaddingTop() == 0) {
                        layout_under_top.startAnimation(topInAnimation);
                    }
                }
                return false;
            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterview, View view,
                                    int i, long l) {
                Intent intent = new Intent(TzbBangForumthreadListActivity2.this,
                        TzbBangForumpostListActivity2.class).putExtra("Tid",String.valueOf(TzbCommonData.hotList.getData().get(i-1).getTid()));
                // TzbDynamicData.setSCROLL(listView.getScrollX(),listView.getScrollY());

                startActivity(intent);
                // LoadActivityWithTabhost(intent,
                // TzbTabMyBangGroup.activityGroup);
            }
        });
    }

    private void initData() {
        if (isCreate || TzbCommonData.hotList == null
                || !TzbCommonData.hotList.isSuccess()) {
            requestInfo();
            isCreate = false;
        } else {
            initListView();
        }
    }

    private void initListView() {
        // 初始化data
        if (data == null) {
            data = new ArrayList<Map<String, Object>>();
        } else {
            data.clear();
        }
        List<Hot> list = TzbCommonData.hotList.getData();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            String subject = list.get(i).getTitle();
            if (subject.length() >= 12) {
                subject = subject.substring(0, 12) + "…";
            }
            map.put("Subject", subject);
            map.put("Lastpost", list.get(i).getSummary().toString());
            // 设置几秒前、几分前、几小时前等
//            String sDateline = YXWDateUtil.getTimeInterval(list.get(i)
//                    .getDateline(), "MM/dd/yyyy HH:mm:ss");
            map.put("Dateline", list.get(i).getDateline());
            data.add(map);
        }
        if (imageAdapter == null) {
            imageAdapter = new ImageAdapter(
                    TzbBangForumthreadListActivity2.this, data, R.layout.tzb_item_forumthread2, new String[]{"Subject", "Lastpost", "Dateline",}, new int[]{R.id.list_item_title,
                    R.id.list_item_context,
                    R.id.list_item_time});
            listView.setAdapter(imageAdapter);
        } else {
            imageAdapter.notifyDataSetChanged();
        }
    }

    // 重载，默认请求新数据
    private void requestInfo() {
        page = 1;
        requestInfo(TzbCommonData.NOPULL_LOAD);
    }

    private void requestInfo(int type) {
        final int type2 = type;
        if (type == TzbCommonData.NOPULL_LOAD) {
            showProgressBar();
        }
        String url = "http://tzt.tzinfo.net/mob/api/ForumHot.ashx?Top=10";
        OutLog.LogE("url", url);
        GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
        galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<HotList>() {
                }.getType();

                HotList forumthreadList = gson.fromJson(arg0, type);
                if (forumthreadList.isSuccess()) {
                    if (type2 == TzbCommonData.PULL_LOAD_MORE) {
                        int size = forumthreadList.getData().size();
                        for (int i = 0; i < size; i++) {
                            TzbCommonData.hotList.getData().add(
                                    forumthreadList.getData().get(i));
                        }
                        if (size < 10) {
                            listView.setPullLoadEnable(false);
                            Toast.makeText(TzbBangForumthreadListActivity2.this,
                                    "已经是最后一页！", Toast.LENGTH_LONG).show();
                        }
                    } else if (type2 == TzbCommonData.PULL_REFLASH
                            || type2 == TzbCommonData.NOPULL_LOAD) {
                        TzbCommonData.hotList = forumthreadList;
                        if (forumthreadList.getData().size() < 10) {
                            listView.setPullLoadEnable(false);
                        } else {
                            listView.setPullLoadEnable(true);
                        }
                    }
                    initListView();
                    onLoadFinish();
                } else {
                    Toast.makeText(TzbBangForumthreadListActivity2.this,
                            "数据加载失败…", Toast.LENGTH_LONG).show();
                }
                removeProgressBar();
            }
        });
    }


    // onclick方法
    @Override
    public void goTabHostBack(View v) {
        // Intent intent = new Intent(this, TzbMyBangAcivity.class);
        // LoadActivityWithTabhost(intent, TzbTabMyBangGroup.activityGroup);
        TzbCommonData.forumthreadList = null;
        TzbCommonData.POSITION = 0;
        this.finish();
    }

    private void onLoadFinish() {
        listView.stopRefresh();
        listView.stopLoadMore();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        listView.setRefreshTime(df.format(new Date()));
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                requestInfo(TzbCommonData.PULL_REFLASH);
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                requestInfo(TzbCommonData.PULL_LOAD_MORE);
            }
        }, 2000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == 1) {
                boolean isOk = data.getBooleanExtra(TzbCommonData.IS_OK, false);
                if (isOk) {
                    requestInfo();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
